import { Body, Controller, Delete, Get, Param, Patch, Post, Query, Req } from '@nestjs/common'
import { ApiBearerAuth, ApiBody, ApiOperation, ApiParam, ApiTags } from '@nestjs/swagger'
import { PagenationPipe } from '@/pipes/pagenation.pipe'
import { formatMenu } from '@/utils/formatMenu'
import { CreateMenuDto } from './dto/create-menu.dto'
import { GetMenuDto } from './dto/get-menu.dto'
import { UpdateMenuDto } from './dto/update-menu.dto'
import { MenuService } from './menu.service'

@Controller('systemManage')
@ApiBearerAuth()
@ApiTags('菜单模块')
export class MenuController {
  constructor(private readonly menuService: MenuService) {}

  @Post('createMenu')
  @ApiOperation({ summary: '创建菜单' })
  @ApiBody({ type: CreateMenuDto })
  create(@Body() createMenuDto: CreateMenuDto) {
    return this.menuService.create(createMenuDto)
  }

  @Get('getAllMenus')
  @ApiOperation({ summary: '菜单列表' })
  findAll() {
    return this.menuService.findAll()
  }

  @Get('getMenuList/v2')
  @ApiOperation({ summary: '树状菜单列表', description: '树状菜单列表' })
  findAllAsTrees(@Query(PagenationPipe) getMenuDto: GetMenuDto) {
    return this.menuService.findAllAsTreesAndCount(getMenuDto)
  }

  @Get('getMenuTree')
  @ApiOperation({ summary: '获取菜单权限列表', description: '编辑角色时获取菜单权限列表' })
  async getMenuTree(@Req() req) {
    const result = await this.menuService.findAllAsTrees()
    return formatMenu(result, req?.user.roles)
  }

  @Get('getAllPages')
  @ApiOperation({ summary: '获取所有页面', description: '获取所有可显示的页面' })
  async getAllPages() {
    const result = await this.menuService.findAll()
    return result.map((item) => item.routeName)
  }

  @Patch('updateMenu/:id')
  @ApiOperation({ summary: '编辑菜单' })
  @ApiBody({ type: UpdateMenuDto })
  update(@Req() req: ReqPayload, @Param('id') id: string, @Body() updateMenuDto: UpdateMenuDto) {
    return this.menuService.update(id, updateMenuDto, req.user)
  }

  @Delete('deleteMenu/:ids')
  @ApiOperation({ summary: '删除菜单' })
  @ApiParam({ name: 'ids', description: '菜单ids' })
  remove(@Param('ids') ids: string) {
    const deleteIds = ids.split(',').map((id) => +id)
    return this.menuService.remove(deleteIds)
  }
}
